package com.wavehi.web;

import com.wavehi.service.IUserService;
import com.wavehi.service.impl.UserServiceImpl;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author WaveHi
 * @Date 26/9/2021 上午 10:56
 * @Version 1.0
 * @Contact HJBWaveHi@163.com
 * @Description
 */
@WebServlet("/userServlet")
public class UserServlet extends BaseServlet{
    //获取业务层对象
    private IUserService ius = new UserServiceImpl();

    /**
     * 无实际意义，仅供开发使用
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

    }

    /**
     * 注销
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void cancel(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //解除会话域中用户信息的绑定
        req.getSession().removeAttribute("username");
        //获取请求转发对象
        RequestDispatcher dispatcher = req.getRequestDispatcher("/page/user/user_login.jsp");
        //转发
        dispatcher.forward(req, resp);
    }

    /**
     * 登录
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //接收用户登录信息
        String username = req.getParameter("username").trim();
        String password = req.getParameter("password").trim();
        boolean remember = Boolean.parseBoolean(req.getParameter("remember"));
        //验证登录信息
        boolean exists = ius.userExists(username, password);
        //转发相应的页面
        if(exists) {
            if(remember) {
                //Get the cookie for username
                Cookie usernameCookie = new Cookie("username", username);
                usernameCookie.setPath("/");
                usernameCookie.setMaxAge(60 * 60 * 24 * 7);
                //回传登录信息给客户端
                resp.addCookie(usernameCookie);
            }
            //绑定用户信息到会话域
            req.getSession().setAttribute("user", ius.getUser(username));
            //获取请求转发对象
            RequestDispatcher requestDispatcher = req.getRequestDispatcher("/page/user/user_index.jsp");
            //转发
            requestDispatcher.forward(req, resp);
        }else {
            //绑定错误信息到请求域
            req.setAttribute("errorMsg", "The user name or password is incorrect.");
            //获取请求转发对象
            RequestDispatcher dispatcher = req.getRequestDispatcher("/page/user/user_login.jsp");
            //转发
            dispatcher.forward(req, resp);
        }
    }
}
